package com.trace.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.trace.entity.Book;
import com.trace.entity.BorrowBook;
import com.trace.service.BookManager;
import com.trace.service.BorrowBookManager;

public class BookAction {

	private BookManager bookBean;
	private BorrowBookManager borrowBookBean;

	@Inject
	public void setBookManager(BookManager bookManager) {
		this.bookBean = bookManager;
	}

	@Inject
	public void setBorrowBookManager(BorrowBookManager borrowBookManager) {
		this.borrowBookBean = borrowBookManager;
	}

	public void borrowBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int customerId = Integer.valueOf((String) request.getSession()
				.getAttribute("userLoginId"));

		String[] bookSelected = request.getParameterValues("bookId");
		int currentbBrrowCount = bookSelected.length;

		if (!borrowBookBean
				.checkBorrowBookCount(customerId, currentbBrrowCount)) {
			request.setAttribute("errorMessage",
					"more than the max borrow count limit.");
			request.getRequestDispatcher("/Message/showMessage").forward(
					request, response);
		} else {
			borrowBookBean.borrowBook(bookSelected, customerId);
			request.getRequestDispatcher("/Book/searchBorrowBook").forward(
					request, response);
		}
	}
	
	public void returnBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String[] borrowSelected = request.getParameterValues("borrowId");
		int customerId = Integer.valueOf((String) request.getSession()
				.getAttribute("userLoginId"));
		borrowBookBean.returnBook(borrowSelected, customerId);

		request.getRequestDispatcher("/Book/searchBorrowBook").forward(
				request, response);
	}
	
	public void searchBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Book book = new Book();
		
		List<Book> listBook = bookBean.findBookByCondition(book);
		
		request.setAttribute("listBook", listBook);
		request.getRequestDispatcher("/books_list.jsp").forward(request, response);
	}
	
	public void searchBorrowBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		int customerId = Integer.valueOf((String) request.getSession()
				.getAttribute("userLoginId"));
		BorrowBook borrowBook = new BorrowBook();
		borrowBook.setCustomerId(customerId);
		List<BorrowBook> listBorrowBook = borrowBookBean
				.searchBorrowBook(borrowBook);
		request.setAttribute("listBook", listBorrowBook);
		request.getRequestDispatcher("/borrow_books_list.jsp").forward(
				request, response);
	}
}
